#    Copyright 2011 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopip/djangoproject/include', '/opt/coopip/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
import os, csv, shutil, datetime, time, reportlab, djangoproject.settings, random
from django.contrib.gis.db import models
from django.contrib.gis.geos import *
from django.http import HttpResponse
from django.contrib import admin
from django.template import Context, loader
import djangoproject.settings
import _mysql as mysql
from models import *
from django import forms
import django
import djangoproject
import COOPIP_Ajax
import COOPIP_Misc
import COOPIP_Form, COOPIP_DynamicTemplate, COOPIP_Authentication, COOPIP_FormIntranet, COOPIP_FormGeneral



def IntranetNoPermission(LoginStatus, Permission):
    t = loader.get_template('/opt/coopip/djangoproject/templates/intranetmainpage.html')
    c = Context({'LoginStatus': LoginStatus, 'Permission': Permission})
    return HttpResponse(t.render(c))


def Department(request, Departmentid):
    """Department is the view that a user sees when they go to their departmental homepage"""
    import datetime
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, 'COOPIP_IntranetUser')
    form=COOPIP_Form.LoginForm()
    department=djangoproject.models.intranet.Department.objects.filter(id=Departmentid)[0]
    DepartmentName=department.Name
    DepartmentBackgroundImage=department.BackgroundImageFileName
    EditorPermission, EditorLoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, [department.EditorGroupName])
    Messages=djangoproject.models.intranet.Message.objects.filter(Department=department).filter(DepartmentPageIndicator=True).exclude(ArchiveIndicator=True).order_by('Priority', '-id')
    MessageList=[]
    for message in Messages:
        Files=djangoproject.models.intranet.MessageFile.objects.filter(Message=message).order_by('FileName')
        FileList=[]
        for file in Files:
            FileList.append([file.id, file.FileName])
        MessageList.append((message.Title, message.MessageText, str(message.CreateDateTime)[:10], message.CreateUsername, FileList))
    CheckEventsForArchival()

    try:
        User=django.contrib.auth.models.User.objects.filter(username=Username)[0]
        StaffIndicator = bool('COOPIP_Staff' in str(User.groups.all()))
    except:
        StaffIndicator=False

    if(StaffIndicator):
        Events=djangoproject.models.intranet.Event.objects.filter(Department=department).exclude(ArchiveIndicator=True).order_by('StartDateTime')
    else:
        Events=djangoproject.models.intranet.Event.objects.filter(Department=department).exclude(ArchiveIndicator=True).exclude(StaffOnlyIndicator=True).order_by('StartDateTime')

    EventList=[]
    for event in Events:
        Temp=[]
        Temp.append(event.Name)
        if(event.StartDateTime):
            Temp.append(event.StartDateTime)
        else:
            Temp.append('')
        if(event.EndDateTime):
            Temp.append(event.EndDateTime)
        else:
            Temp.append('')
        if(event.Resource):
            Temp.append(str(event.Resource)[:10])
        else:
            Temp.append('')
        EventList.append(Temp)
    #raise(Exception('IT Testing in progress, should be ok in 5 mins.'))
    if(department.Name in ['Technology']):
        DisplayAdminLink=True
    else:
        DisplayAdminLink=False
    t = loader.get_template('/opt/coopip/djangoproject/templates/intranetdepartment.html')
    c = Context({'LoginStatus': LoginStatus, 'form': form, 'Permission': Permission,
                 'DepartmentName': DepartmentName, 'MessageList':MessageList, 'EditorPermission':EditorPermission,
                 'DepartmentBackgroundImage': DepartmentBackgroundImage, 'DisplayAdminLink':DisplayAdminLink,
                 'EventList':EventList })
    return HttpResponse(t.render(c))





def MessageFileView(request, MessageFileid):
    import datetime
    # FIXME Breaks when non-department employees attempt to view file; revert when option to be viewed by all employees can be added
    try:
        messageFile=djangoproject.models.intranet.MessageFile.objects.filter(id=MessageFileid)[0]
        message=messageFile.Message
        Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, ['COOPIP_IntranetUser'])
    #try:
    #    messageFile=djangoproject.models.intranet.MessageFile.objects.filter(id=MessageFileid)[0]
    #    message=messageFile.Message
    #    department=message.Department
    #    GroupList=[department.GroupName, department.EditorGroupName]
    #    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, GroupList)
    except AssertionError:
        Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, ['COOPIP_InvalidGroupSelected__ThisGroupShouldNotExist'])
    if((not Permission) or (not messageFile)):
        #raise(Exception(str(messageFile)))
        t = loader.get_template('/opt/coopip/djangoproject/templates/intranetdepartment.html')
        c = Context({'LoginStatus': LoginStatus, 'Permission': Permission})
        return HttpResponse(t.render(c))

    import mimetypes
    ContentType=mimetypes.guess_type(messageFile.FileName)[0]
    LocalFile=open('/opt/coopip/media/message/' + str(MessageFileid))
    response=HttpResponse(content=LocalFile.read())
    response['Content-Type']=ContentType
    response['Content-Disposition']='attachment; filename=' + messageFile.FileName
    return response



def Message(request):
    """Message is the View that allows users to edit Messages displayed for Departments or on the Intranet Main Page"""
    import datetime
    EditorGroups=[]
    for department in djangoproject.models.intranet.Department.objects.all():
        EditorGroups.append(department.EditorGroupName)
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, EditorGroups)
    if(not Permission):  
        return IntranetNoPermission(LoginStatus, Permission)
    SpecialBuildFormDataDict={'request': request}
    try:
        User=django.contrib.auth.models.User.objects.filter(username=Username)[0]
        StaffIndicator = bool('COOPIP_Staff' in str(User.groups.all()))
    except:
        StaffIndicator=False
    SpecialBuildFormDataDict['StaffIndicator']=StaffIndicator
 
    form=COOPIP_Form.BuildDynamicForm(request, 'IntranetMessage', SpecialBuildFormDataDict)
    Message, Event=COOPIP_FormIntranet.ProcessMessageForm(form, Username, request)
    #Now, rebuild the form in case a new message or event was created, so that it will be selected
    if(Event):
        SpecialBuildFormDataDict['Event']=Event
    if(Message):
        SpecialBuildFormDataDict['Message']=Message
    form=COOPIP_Form.BuildDynamicForm(request, 'IntranetMessage', SpecialBuildFormDataDict)
    form=COOPIP_FormIntranet.PopulateMessageForm(form, Message, Event)
    if(Message):
        Files=djangoproject.models.intranet.MessageFile.objects.filter(Message=Message).order_by('FileName')
        FileList=[]
        for file in Files:
            FileList.append([file.id, file.FileName])
    else:
        FileList=[]
    t = loader.get_template('/opt/coopip/djangoproject/templates/intranetmessage.html')
    c = Context({'LoginStatus': LoginStatus, 'form': form, 'Permission': Permission,
                 'FileList': FileList, 'StaffIndicator': StaffIndicator})
    return HttpResponse(t.render(c))



def CheckMessagesForArchival():    
    Messages=djangoproject.models.intranet.Message.objects.filter(ExpireDateTime__lte=datetime.datetime.now()).exclude(ArchiveIndicator=True)
    for message in Messages:
        message.ArchiveIndicator=True
        message.save()


def CheckEventsForArchival():    
    Yesterday=datetime.datetime.now() - datetime.timedelta(days=1)
    Events=djangoproject.models.intranet.Event.objects.filter(StartDateTime__lte=Yesterday).exclude(ArchiveIndicator=True)
    for event in Events:
        if(not event.EndDateTime or event.EndDateTime < Yesterday):
            if(not event.ArchiveOverrideDateTime or event.ArchiveOverrideDateTime < Yesterday):
                event.ArchiveIndicator=True
                event.save()
    
    


def index(request):
    import datetime
    Permission, LoginStatus, Username = COOPIP_Authentication.COOPIPAuthenticate(request, 'COOPIP_IntranetUser')
    Departments=djangoproject.models.intranet.Department.objects.all().exclude(Name='FrontPageBackgroundOnly').order_by('Name')
    DepartmentList=[]
    for department in Departments:
        DepartmentList.append((department.id, department.Name))
    CheckMessagesForArchival()
    Messages=djangoproject.models.intranet.Message.objects.filter(FrontPageIndicator=True).exclude(ArchiveIndicator=True).order_by('Priority', '-id')
    MessageList=[]
    for message in Messages:
        Files=djangoproject.models.intranet.MessageFile.objects.filter(Message=message).order_by('FileName')
        FileList=[]
        for file in Files:
            FileList.append([file.id, file.FileName])
        MessageList.append((message.Title, message.MessageText, str(message.CreateDateTime)[:10], message.CreateUsername, FileList))
    form=COOPIP_Form.LoginForm()
    DepartmentBackgroundImage=djangoproject.models.intranet.Department.objects.filter(Name='FrontPageBackgroundOnly')[0].BackgroundImageFileName
    CheckEventsForArchival()
    try:
        User=django.contrib.auth.models.User.objects.filter(username=Username)[0]
        StaffIndicator = bool('COOPIP_Staff' in str(User.groups.all()))
    except:
        StaffIndicator=False
    if(StaffIndicator):
        Events=djangoproject.models.intranet.Event.objects.filter(FrontPageIndicator=True).exclude(ArchiveIndicator=True).exclude(DoNotShowBeforeDateTime__gte=datetime.datetime.now()).order_by('StartDateTime')
    else:
        Events=djangoproject.models.intranet.Event.objects.filter(FrontPageIndicator=True).exclude(ArchiveIndicator=True).exclude(StaffOnlyIndicator=True).exclude(DoNotShowBeforeDateTime__gte=datetime.datetime.now()).order_by('StartDateTime')
    
    EventList=[]
    for event in Events:
        Temp=[]
        Temp.append(event.Name)
        if(event.StartDateTime):
            Temp.append(event.StartDateTime)
        else:
            Temp.append('')
        if(event.EndDateTime):
            Temp.append(event.EndDateTime)
        else:
            Temp.append('')
        if(event.Resource):
            Temp.append(str(event.Resource)[:10])
        else:
            Temp.append('')
        EventList.append(Temp)
    t = loader.get_template('/opt/coopip/djangoproject/templates/intranetmainpage.html')
    c = Context({'LoginStatus': LoginStatus, 'form': form, 'Permission': Permission, 'DepartmentList': DepartmentList, 'MessageList': MessageList,
                 'DepartmentBackgroundImage': DepartmentBackgroundImage, 'EventList':EventList})
    return HttpResponse(t.render(c))








